<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/6/30
 * Time: 11:33
 */

namespace ElementVip\JwOms\Services;

use ElementVip\Component\Product\Models\Product;
use ElementVip\JwOms\Models\OmsSyncLog;
use DB;

class GoodsService
{
    /**
     * 同步库存
     * @param $file
     */
    public function syncStock($file, $type)
    {
        $fileUrl = '/storage/' . strstr($file, 'oms');
        $lines = file($file);
        $failed = [];
        $success = [];

        foreach ($lines as $key => $item) {
            $data = explode(';', $item);
            $sku = $data[3];
            $inventory = $data[5];
            if (!$product = Product::where('sku', $sku)->first()) {
                //产品不存在,记录日志
                $failed[] = '产品 ' . $sku . ' 不存在';
                continue;
            }

            if ($type == 'Stock') { //如果是同步库存
                $product->store_nums = $inventory;
                if ($inventory < 1) {
                    $product->is_show = 0;
                } else {
                    $product->is_show = 1;
                }

            } else {       //否则增量库存
                $num = $product->store_nums + $inventory;
                if ($num < 1) {
                    $product->is_show = 0;
                } else {
                    $product->is_show = 1;
                }
                $product->store_nums = $num < 0 ? 0 : $num;
            }

            $product->save();

            DB::statement('UPDATE el_goods  SET store_nums = ( SELECT SUM(store_nums) FROM el_goods_product WHERE goods_id=el_goods.id) where id=' . $product->goods_id);

            $success[] = '产品: ' . $sku . ' 库存同步成功';

        }

        if (count($failed) > 0 OR count($success) > 0) {
            OmsSyncLog::create([
                'type' => $type,
                'file' => $fileUrl,
                'success_message' => $success,
                'failed_message' => $failed
            ]);
        }
    }
}